package com.ruyuan.eshop.construction.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruyuan.eshop.common.annotation.ParamsValidate;
import com.ruyuan.eshop.common.constants.RocketMqConstant;
import com.ruyuan.eshop.common.enums.ProductTypeEnum;
import com.ruyuan.eshop.common.enums.construction.AuditTypeEnum;
import com.ruyuan.eshop.common.exception.CommonErrorCodeEnum;
import com.ruyuan.eshop.common.exception.ProductBizException;
import com.ruyuan.eshop.common.message.UpdateProductMessage;
import com.ruyuan.eshop.common.utils.ParamCheckUtil;
import com.ruyuan.eshop.construction.builder.FullDraftData;
import com.ruyuan.eshop.construction.builder.FullProductData;
import com.ruyuan.eshop.construction.builder.ProductBuilder;
import com.ruyuan.eshop.construction.builder.ProductDraftBuilder;
import com.ruyuan.eshop.construction.converter.ProductConverter;
import com.ruyuan.eshop.construction.domain.dto.ItemDetailDTO;
import com.ruyuan.eshop.construction.domain.dto.ProductDTO;
import com.ruyuan.eshop.construction.domain.dto.SaleSkuDTO;
import com.ruyuan.eshop.construction.domain.dto.SkuDetailDTO;
import com.ruyuan.eshop.construction.domain.dto.SkuInfoDTO;
import com.ruyuan.eshop.construction.domain.dto.SkuPriceResultDTO;
import com.ruyuan.eshop.construction.domain.entity.AttributeExtendDO;
import com.ruyuan.eshop.construction.domain.entity.ItemInfoDO;
import com.ruyuan.eshop.construction.domain.entity.ItemShelfLifeDO;
import com.ruyuan.eshop.construction.domain.entity.ItemVideoImgDO;
import com.ruyuan.eshop.construction.domain.entity.SkuDetailDO;
import com.ruyuan.eshop.construction.domain.entity.SkuInfoDO;
import com.ruyuan.eshop.construction.domain.request.ProductRequest;
import com.ruyuan.eshop.construction.domain.request.QueryItemListRequest;
import com.ruyuan.eshop.construction.domain.request.QuerySaleSkuRequest;
import com.ruyuan.eshop.construction.domain.request.QuerySkuListRequest;
import com.ruyuan.eshop.construction.domain.request.SkuPriceRequest;
import com.ruyuan.eshop.construction.manager.ProductNoManager;
import com.ruyuan.eshop.construction.mq.producer.DefaultProducer;
import com.ruyuan.eshop.construction.repository.ProductAuditRepository;
import com.ruyuan.eshop.construction.repository.ProductInfoRepository;
import com.ruyuan.eshop.construction.service.ProductService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductNoManager productNoManager;

    @Resource
    private ProductInfoRepository productInfoRepository;

    @Resource
    private ProductAuditRepository productAuditRepository;


    @Resource
    private ProductConverter productConverter;


    @Autowired
    private DefaultProducer defaultProducer;

    /**
     * 建品/编辑商品
     *
     * @param productRequest
     * @return com.ruyuan.eshop.construction.domain.dto.SaveOrUpdateProductDTO
     * @author zhonghuashishan
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    @ParamsValidate
    public ProductDTO product(ProductRequest productRequest) {
        // 入参检查
        checkProductRequestParam(productRequest);

        // 商品数据处理
        ProductDTO productDTO = handleProduct(productRequest);

        // 返回商品信息
        return productDTO;
    }

    /**
     * 修改商品价格接口
     *
     * @param skuPriceRequest
     * @return com.ruyuan.eshop.construction.domain.dto.UpdatePriceDTO
     * @author zhonghuashishan
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    @ParamsValidate
    public SkuPriceResultDTO updatePrice(SkuPriceRequest skuPriceRequest) {
        // 入参检查
        checkUpdatePriceRequestParam(skuPriceRequest);

        // 商品数据处理
        handlePrice(skuPriceRequest);

        // 发送消息通知订阅方 价格修改，需要审核，在审核通过之后再发送消息

        // 返回商品信息
        return new SkuPriceResultDTO(true);
    }
    /**
     * 查询可售sku
     *
     * @param querySaleSkuRequest 卖家相关信息
     * @return  可售sku列表
     */
    @Override
    public SaleSkuDTO getSaleSku(QuerySaleSkuRequest querySaleSkuRequest) {
        // 验证查询入参
        checkSaleSkuRequestParam(querySaleSkuRequest);
        // 查询可售的列表
        List<SkuInfoDTO> skuInfoDTOList =
                productConverter.converterSkuInfoList(productInfoRepository.querySkuSellerList(querySaleSkuRequest));
        //返回可售sku列表
        return new SaleSkuDTO(skuInfoDTOList);
    }
    /**
     * 获取商品价格相关信息
     * @param skuPriceRequest
     */
    private FullDraftData handlePrice(SkuPriceRequest skuPriceRequest) {
        // 构建全量商品对象
        FullProductData fullProductData = buildFullProductData(skuPriceRequest);
        // 需要审核，则正式表中的数据不变更，只新增草稿表记录
        FullDraftData fullDraftData = buildDraft(fullProductData, AuditTypeEnum.PRICE.getCode());
        // 保存草稿信息
        productAuditRepository.saveDraft(fullDraftData);

        return fullDraftData;
    }

    /**
     * 构建全量商品对象
     * @param skuPriceRequest
     * @return
     */
    private FullProductData buildFullProductData(SkuPriceRequest skuPriceRequest){
        SkuInfoDO skuInfoDO = productInfoRepository.getSkuInfoBySkuId(skuPriceRequest.getSkuId());
        if (!Objects.isNull(skuPriceRequest.getBasePrice())){
            skuInfoDO.setBasePrice(skuPriceRequest.getBasePrice());
        }
        if (!Objects.isNull(skuPriceRequest.getVipPrice())){
            skuInfoDO.setVipPrice(skuPriceRequest.getVipPrice());
        }
        // 查询商品的
        ItemInfoDO itemInfoDO = productInfoRepository.selectByItemId(skuInfoDO.getItemId());
        return new FullProductData(itemInfoDO, Collections.singletonList(skuInfoDO));
    }

    /**
     * 验证 修改价格接口入参
     * @param skuPriceRequest
     */
    private void checkUpdatePriceRequestParam(SkuPriceRequest skuPriceRequest) {
        if (Objects.isNull(skuPriceRequest.getBasePrice()) && Objects.isNull(skuPriceRequest.getVipPrice())){
            throw new ProductBizException(CommonErrorCodeEnum.SERVER_ILLEGAL_ARGUMENT_ERROR);
        }
    }

    /**
     * 查询可售商品入参检查
     *
     * @param querySaleSkuRequest
     * @return void
     * @author zhonghuashishan
     */
    private void checkSaleSkuRequestParam(QuerySaleSkuRequest querySaleSkuRequest) {
        ParamCheckUtil.checkObjectNonNull(querySaleSkuRequest);
        ParamCheckUtil.checkStringNonEmpty(querySaleSkuRequest.getSellerId());
    }

    /**
     * 商品数据处理
     *
     * @param productRequest
     * @return void
     * @author zhonghuashishan
     */
    private ProductDTO handleProduct(ProductRequest productRequest) {
        // 构建商品的全量信息
        FullProductData fullProductData = buildProduct(productRequest);

        // 是否构建填充 itemId
        Boolean createFlag = whetherBuildProductItemId(fullProductData);

        // 判断是否需要审核，根据配置的sku或者item或者品类信息，如果需要审核，只处理草稿表中的数据，正式表中的数据不动
        if (productAuditRepository.needAudit(fullProductData, createFlag)){
            // 需要审核，则正式表中的数据不变更，只新增草稿表记录
            FullDraftData fullDraftData = buildDraft(fullProductData, AuditTypeEnum.GOODS.getCode());

            // 保存草稿信息
            productAuditRepository.saveDraft(fullDraftData);
            return new ProductDTO(null, null);
        }

        // 如果不需要审核，则保存商品信息
        this.saveOrUpdateDBProduct(fullProductData, createFlag);

        // 发送消息通知订阅方
        sendUpdateProductMessage(fullProductData);

        // 返回商品返回结果
        return new ProductDTO(fullProductData.getItemInfoDO().getItemId(),
                buildProductSkuIds(fullProductData));
    }

    private List<String> buildProductSkuIds(FullProductData fullProductData) {

        List<String> skuIds = fullProductData.getSkuInfoDOList()
                .stream()
                .map(skuInfoDO -> skuInfoDO.getSkuId())
                .collect(Collectors.toList());
        return skuIds;
    }

    private void sendUpdateProductMessage(FullProductData fullProductData) {
        // 构建商品修改消息对象
        UpdateProductMessage message = buildUpdateProductMessage(fullProductData);

        //发送商品修改消息
        defaultProducer.sendMessage(RocketMqConstant.PRODUCT_UPDATE_TOPIC,
                JSONObject.toJSONString(message), "商品修改");
    }

    private UpdateProductMessage buildUpdateProductMessage(FullProductData fullProductData) {
        return new UpdateProductMessage(fullProductData.getItemInfoDO().getItemId(),
                buildProductSkuIds(fullProductData));
    }

    /**
     * 是否需要构建商品的ItemId
     * @param fullProductData
     * @return
     */
    private Boolean whetherBuildProductItemId(FullProductData fullProductData){
        // ITEM信息
        ItemInfoDO itemInfoDO = fullProductData.getItemInfoDO();
        // 新增
        if(StringUtils.isEmpty(itemInfoDO.getItemId())) {
            // 保质期
            ItemShelfLifeDO itemShelfLifeDO = fullProductData.getItemShelfLifeDO();
            String itemId = createItemId();
            // 赋值itemId
            itemInfoDO.setItemId(itemId);
            itemShelfLifeDO.setItemId(itemId);
            // SKU信息
            List<SkuInfoDO> skuInfoDOList = fullProductData.getSkuInfoDOList();
            for (SkuInfoDO skuInfoDO : skuInfoDOList) {
                String skuId = productNoManager.generateProductNo(ProductTypeEnum.SKU.getCode());
                skuInfoDO.setSkuId(skuId);
                skuInfoDO.setItemId(itemId);
            }
            // 视频图片
            List<ItemVideoImgDO> itemVideoImgDOList = fullProductData.getItemVideoImgDOList();
            for (ItemVideoImgDO itemVideoImgDO : itemVideoImgDOList) {
                itemVideoImgDO.setItemId(itemId);
            }
            // 属性扩展
            AttributeExtendDO attributeExtendDO = fullProductData.getAttributeExtendDO();
            attributeExtendDO.setParticipateId(itemInfoDO.getItemId());
            attributeExtendDO.setParticipateType(ProductTypeEnum.ITEM.getCode());
            return true;
        }
        return false;
    }

    /**
     * 创建ItemId
     * @return ItemId
     */
    private String createItemId(){
        String itemId = productNoManager.generateProductNo(ProductTypeEnum.ITEM.getCode());
        return itemId;
    }

    /**
     * 新增或者修改商品相关信息
     * @param fullProductData
     * @param createFlag
     */
    @Override
    public void saveOrUpdateDBProduct(FullProductData fullProductData, Boolean createFlag) {
        // 新增
        if (createFlag) {
            productInfoRepository.saveItemInfo(fullProductData);
        } else {
            //修改
            productInfoRepository.updateItemInfo(fullProductData);
        }
    }

    /**
     * 建品/编辑商品入参检查
     *
     * @param productRequest
     * @return void
     * @author zhonghuashishan
     */
    private void checkProductRequestParam(ProductRequest productRequest) {
        ParamCheckUtil.checkObjectNonNull(productRequest);

        // 商品基本信息
        ProductRequest.ItemBaseRequest itemBaseRequest = productRequest.getItemBaseRequest();
        ParamCheckUtil.checkObjectNonNull(itemBaseRequest);

        // 存储信息
        ProductRequest.ItemStorageRequest itemStorageRequest = productRequest.getItemStorageRequest();
        ParamCheckUtil.checkObjectNonNull(itemStorageRequest);

        // 品控信息
        ProductRequest.ShelfLifeRequest shelfLifeRequest = productRequest.getShelfLifeRequest();
        ParamCheckUtil.checkObjectNonNull(shelfLifeRequest);

        // 图文信息
        List<ProductRequest.ItemVideoImgRequest> itemVideoImgRequestList = productRequest.getItemVideoImgRequestList();
        ParamCheckUtil.checkObjectNonNull(itemVideoImgRequestList);

        // 销售信息
        ProductRequest.ItemSaleRequest itemSaleRequest = productRequest.getItemSaleRequest();
        ParamCheckUtil.checkObjectNonNull(itemSaleRequest);

        // 推广信息
        ProductRequest.ItemPopularizeRequest itemPopularizeRequest = productRequest.getItemPopularizeRequest();
        ParamCheckUtil.checkObjectNonNull(itemPopularizeRequest);
    }
    /**
     * 根据商品数据构建商品草稿数据
     *
     * @param fullProductData
     * @param auditType
     * @return com.ruyuan.eshop.construction.builder.FullDraftData
     * @author zhonghuashishan
     */
    private FullDraftData buildDraft(FullProductData fullProductData, Integer auditType) {
        ProductDraftBuilder productDraftBuilder = new ProductDraftBuilder(fullProductData);
        FullDraftData fullDraftData = productDraftBuilder.buildDraftMain(auditType)
                .buildDraftImgList()
                .build();
        return fullDraftData;
    }

    private FullProductData buildProduct(ProductRequest productRequest) {
        ProductBuilder productBuilder = new ProductBuilder(productRequest);
        FullProductData fullProductData = productBuilder.buildItemInfo()
                .buildItemShelfLife()
                .buildItemVideoImgList()
                .buildSkuInfoList()
                .buildSkuBarCodeRelationList()
                .buildCspuSkuRelation()
                .buildAttributeExtend()
                .buildQualityControl()
                .build();

        return fullProductData;
    }

    /**
     * 根据itemId查询item信息
     *
     * @param queryItemListRequest
     * @return
     */
    @Override
    @ParamsValidate
    public List<ItemDetailDTO> listItemByItemIds(QueryItemListRequest queryItemListRequest) {
        return productConverter.converterItemDetailDOList(
                productInfoRepository.listItemByItemIds(queryItemListRequest));
    }



    /**
     *  批量查询商品的SKU信息
     * @param querySkuListRequest
     * @return
     */
    @Override
    public List<SkuDetailDTO> listSkus(QuerySkuListRequest querySkuListRequest) {
        List<SkuDetailDO> skuDetailList = productInfoRepository.listSkus(querySkuListRequest);

        // 对象转换
        return productConverter.converterSkuDetailList(skuDetailList);
    }



}
